package cn.calm.xhtml.impl.fun;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import cn.calm.xhtml.annotation.Attribute;
import cn.calm.xhtml.annotation.Tag;
import cn.calm.xhtml.api.exception.XhtmlException;
import cn.calm.xhtml.api.service.AbstraceNodeProcess;
import cn.calm.xhtml.api.service.XhtmlContext;
import cn.calm.xhtml.util.ValueUtil;
@Tag(namespace = "http://www.calm.cn/xhtml/extras/core", attributes = {
		@Attribute(name = "var", description = "路径变量", template = "<label></label><input name=\"url\"/>"),
		@Attribute(name = "value", description = "路径值", template = "<label></label><input name=\"value\"/>")})
public class Url extends AbstraceNodeProcess {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String var;

	@Override
	public void processNode(XhtmlContext context) throws XhtmlException {
		var = getAttr("var");
		if (var == null) {
			throw new XhtmlException("tag " + getName() + " attr: var is null");
		}
		String value = getAttr("value");
		if (value == null) {
			throw new XhtmlException("tag " + getName()
					+ " attr: value is null");
		}
		
		if (value.startsWith("/")) {
			value = "${#application.getContextPath()}" + value;
		}
		String value2 = ValueUtil.getValue(value, context);
		int indexOf = value2.indexOf('?');
		StringBuilder temp=new StringBuilder();
		if (indexOf >= 0) {
			temp.append(value2.substring(0, indexOf));
			String parameter = value2.substring(indexOf+1);
			String[] split = parameter.split("&");
			int i=0;
			for(String sp:split){
				if(i==0){
					temp.append("?");
				}else{
					temp.append("&");
				}
				i++;
				String[] split2 = sp.split("=");
				temp.append(split2[0]);
				temp.append("=");
				try {
					temp.append(URLEncoder.encode(split2[1], "UTF-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		} else {
			temp.append(value2);
		}
		context.setValue(var, temp.toString());
		processChildren(context);
	}

}
